package com.yxsk.endpoint.demo.original.job;

import com.yxsk.relay.job.component.common.exception.RelayJobException;
import com.yxsk.relay.job.component.common.vo.Endpoint;
import com.yxsk.relay.job.component.common.vo.EndpointExecuteResult;
import com.yxsk.relay.job.component.common.vo.PartitionInfo;
import com.yxsk.relay.job.component.endpoint.handle.Collectable;
import com.yxsk.relay.job.component.endpoint.handle.JobExecutor;
import com.yxsk.relay.job.component.endpoint.handle.Partitionable;
import com.yxsk.relay.job.component.endpoint.handle.anno.JobHandler;
import com.yxsk.relay.job.component.endpoint.log.logger.RelayJobLoggerFactory;
import org.slf4j.Logger;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;

@JobHandler("complexJobDemo")
public class ComplexJobDemo implements JobExecutor, Collectable, Partitionable {

    private static final Logger logger = RelayJobLoggerFactory.getLogger(ComplexJobDemo.class);

    @Override
    public String collect(List<EndpointExecuteResult> executeResults) throws RelayJobException {

        logger.debug("BigDataJobDemo开始收集任务结果");

        logger.debug("BigDataJobDemo执行结果列表：{}", executeResults);

        return "数据计算结束";
    }

    @Override
    public String execute(String param) throws RelayJobException {
        logger.debug("数据计算中, 执行参数: {}", param);

        try {
            Thread.sleep(new Random().nextInt(5000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        logger.debug("数据计算任务执行完成");
        return "calculate complete > " + Thread.currentThread().getName();
    }

    @Override
    public List<PartitionInfo> partition(List<Endpoint> availableEndpoints, String executeParam) {
        logger.info("BigDataJobDemo收到分片请求, 端点列表：" + availableEndpoints);
        List<PartitionInfo> partitionInfos = new ArrayList<>();
        availableEndpoints.stream().forEach(endpoint -> {
            PartitionInfo info = new PartitionInfo();
            info.setEndpoint(endpoint);
            info.setExecuteParam(UUID.randomUUID().toString());
            partitionInfos.add(info);
        });
        logger.debug("BigDataJobDemo分片结果：{}", partitionInfos);
        return partitionInfos;
    }

}
